package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.prop.WeiPayProperties;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeiPatService;
import com.atguigu.yygh.order.utis.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utis.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeiPayServiceImpl implements WeiPatService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private WeiPayProperties weiPayProperties;

    @Autowired
    private RefundInfoServiceImpl refundInfoService;


//    通过OrderId获取Url地址
    @Override
    public String createNative(Long orderId) {
//        1.根据订单id(去数据库)获取订单信息
        OrderInfo orderInfo = orderInfoService.getById(orderId);
//        2.保存支付记录信息
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
//        3.请求微信付曲奇获取微信支付的url地址
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weiPayProperties.getAppid()); //公众号Id
        paramMap.put("mch_id",weiPayProperties.getPartnerkey());    //商户号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());    //随机字符串

        Date reserveDate = orderInfo.getReserveDate();
        String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
        String body = reserveDateString + "就诊"+ orderInfo.getDepname();
        paramMap.put("body", body); //商品描述信息

        paramMap.put("out_trade_no",orderInfo.getOutTradeNo()); //商务号
        paramMap.put("total_fee", "1"); //支付金额
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify"); //回调地址
        paramMap.put("trade_type", "NATIVE"); //支付类型

        try {
//            将Map集合转换为xml字符串
            String xmlString = WXPayUtil.generateSignedXml(paramMap, weiPayProperties.getPartnerkey());
            httpClient.setXmlParam(xmlString);
            httpClient.post();

            String content = httpClient.getContent();
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(content);

//        4.返回给前端地址
            return "url";
        }catch (Exception ex){
            return "";
        }

    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            //1、封装参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据，转成Map
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、返回
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

//TODO    微信退款
    @Override
    public boolean refund(Long orderId) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentService.getOne(queryWrapper);
        RefundInfo refundInfo =  refundInfoService.saveRefundInfo(paymentInfo);

        //        已退款
        if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
//            已退款
            System.out.println("退款成功");
            return  true;
        }
//        执行微信退款
        System.out.println("退款成功");


        return false;
    }
}
